package adfc2.entities;

import adfc2.core.Entity;
import adfc2.core.Item;
import adfc2.core.World;

/**
 * Объект-здание. На карте находится в левом ближнем углу:
 * <p/>
 * PPP
 * PPP
 * BPP
 * <p/>
 * где P --- BuildingPart
 */
public abstract class Building extends Entity {
    public final int width;
    public final int height;
    public final Item[] components;
    private BuildingPart[] parts;
    private final boolean[] passmap;

    /**
     * Example usage: genPassmap("##.",
     * "#.#",
     * ".#.")
     */
    protected static boolean[] genPassmap(String... vals) {
        boolean[] passmap = new boolean[vals.length * vals[0].length()];
        for (int i = 0; i < vals.length; i++) {
            String val = vals[i];
            for (int j = 0; j < val.length(); j++) {
                passmap[(vals.length - i - 1) * val.length() + j] = val.charAt(j) == '.';
            }
        }
        return passmap;
    }

    /**
     * @param passmap    Карта проходимости здания (true --- можно пройти)
     * @param components Предметы, используемые при строительстве здания (блоки, детали, и т.п.)
     */
    public Building(int width, int height, boolean[] passmap, Item[] components) {
        this.width = width;
        this.height = height;
        this.passmap = passmap;
        this.components = components;
        for (Item component : components) {
            assert component.owner == null;
            component.owner = this;
        }
        parts = new BuildingPart[width * height - 1];
        for (int i = 0; i < parts.length; i++) {
            parts[i] = new BuildingPart(this);
        }
    }

    @Override
    public void register(int xy) {
        super.register(xy);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int subxy = World.mkxy(getX() + x, getY() + y);
                if (x != 0 || y != 0) {
                    parts[y * height + x - 1].register(subxy);
                }
                world().blocks[subxy] |= World.MASK_BUILDING;
                if (!passmap[y * height + x]) {
                    world().blocks[subxy] |= World.MASK_IMPASSABLE;
                }
            }
        }
    }
}
